<template>
  <van-icon
    :color="value ? '#ffa500' : ''"
    :name="value ? 'star' : 'star-o'"
    @click="onCollect"
    :loading="loading"
  />
</template>

<script>
import { addCollect, deleteCollect } from "@/api/article.js";
export default {
  name: "collectArticle",
  props: {
    value: {
      type: Boolean,
      required: true,
    },

    article_id: {
      type: [Number, String, Object],
      required: true,
    },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    async onCollect() {
      // 开始请求
      this.loading = true;
      try {
        // 是否收藏
        if (this.value) {
          // 父组件 传递articleId
          await deleteCollect(this.article_id);
        } else {
          await addCollect(this.article_id);
        }
        // 更新视图
        this.$emit("input", !this.value);
        this.$toast.success(this.value ? "取消收藏" : "收藏成功");
      } catch (err) {
        this.$toast("操作失败，请重试");
      }
      // 请求结束
      this.loading = false;
    },
  },
};
</script>

<style scoped lang='less'>
.collected {
  color: #ff8344;
}
</style>